package com.dwjm.client;

import com.dwjm.ConnectionDatabaseForMySQLUserJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ConsumerDaoImpl implements ConsumerDao {

    @Override
    public boolean register(Consumer consumer) {
        String sql = "INSERT INTO t_consumer(account, password1, realname, idcard, tel, age, province, city, district, addr, state) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
        try (Connection conn = ConnectionDatabaseForMySQLUserJdbc.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, consumer.getAccount());
            ps.setString(2, consumer.getPassword1());
            ps.setString(3, consumer.getRealname());
            ps.setString(4, consumer.getIdcard());
            ps.setString(5, consumer.getTel());
            ps.setInt(6, consumer.getAge());
            ps.setString(7, consumer.getProvince());
            ps.setString(8, consumer.getCity());
            ps.setString(9, consumer.getDistrict());
            ps.setString(10, consumer.getAddr());
            return ps.executeUpdate() > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    @Override
    public Consumer login(String account, String password) {
        Connection conn = ConnectionDatabaseForMySQLUserJdbc.getConnection();
        try {
            String sql = "SELECT * FROM t_consumer WHERE account=? AND password1=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, account);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Consumer(
                        rs.getInt("id"),
                        rs.getString("account"),
                        rs.getString("password1"),
                        rs.getString("realname"),
                        rs.getString("idcard"),
                        rs.getString("tel"),
                        rs.getInt("age"),
                        rs.getString("province"),
                        rs.getString("city"),
                        rs.getString("district"),
                        rs.getString("addr"),
                        rs.getInt("state")
                );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
